package contrib

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/pkg/errors"
	"go.uber.org/zap"
	"myCloud/constant"
	"myCloud/logsvr"
	"strconv"
)

type ErrMsgRsp struct {
	Code    int    `json:"code"`
	Message string `json:"msg"`
}

func AbortReq(c *gin.Context, httpcode int, msg string, errs ...error) {
	setReason(c, msg)
	if len(errs) > 0 {
		for _, item := range errs {
			if item != nil {
				_ = c.Error(item)
			}
		}
	}

	rsp := ErrMsgRsp{
		Code:    httpcode,
		Message: msg,
	}
	c.JSON(httpcode, rsp)
	c.Abort()
}

func setReason(c *gin.Context, reason string) {
	keys := c.MustGet(constant.LogFields).(*logsvr.LogFields)
	keys.AddField(zap.String("reason", reason))
}

func NextReq(c *gin.Context, httpcode int, msg string, errs ...error) {
	setReason(c, msg)
	if len(errs) > 0 {
		for _, item := range errs {
			_ = c.Error(item)
		}
	}

	rsp := ErrMsgRsp{
		Code:    httpcode,
		Message: msg,
	}
	c.JSON(httpcode, rsp)
	c.Next()
}

func ValidateParam(c *gin.Context, p string) (id uint, err error) {
	param, err := strconv.Atoi(c.Param(p))
	msg := fmt.Sprintf("params [%s] parse to uint int failed.", p)
	return uint(param), errors.Wrap(err, msg)
}
